package com.yxx.service.Impl;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.extra.servlet.ServletUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.yxx.annotation.OptLogger;
import com.yxx.constant.CommonConstant;
import com.yxx.constant.OptTypeConstant;
import com.yxx.entity.Message;
import com.yxx.entity.SiteConfig;
import com.yxx.entityModel.vo.Result.PageResult;
import com.yxx.entityModel.vo.Result.ResponseResult;
import com.yxx.entityModel.vo.query.MessageQuery;
import com.yxx.entityModel.vo.request.CheckRequest;
import com.yxx.entityModel.vo.request.MessageRequest;
import com.yxx.entityModel.vo.response.MessageBackResponse;
import com.yxx.entityModel.vo.response.MessageResponse;
import com.yxx.mapper.MessageMapper;
import com.yxx.service.CarouselService;
import com.yxx.service.MessageService;
import com.yxx.service.SiteConfigService;
import com.yxx.utils.BeanCopyUtils;
import com.yxx.utils.HTMLUtils;
import com.yxx.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yuxiangxun
 * @date 2025/2/4
 * @apiNote
 */
@Service
@Slf4j
public class MessageServiceImpl extends ServiceImpl<MessageMapper,Message> implements MessageService {

    @Resource
    private MessageMapper messageMapper;

    @Resource
    private HttpServletRequest httpServletRequest;

    @Resource
    private SiteConfigService siteConfigService;

    /**
     * 查看留言列表
     * @return
     */
    @Override
    public List<MessageResponse> listMessageVO() {
        // 查询留言列表
        return messageMapper.selectMessageVOList();
    }

    @Override
    public PageResult<MessageBackResponse> messageBackList(MessageQuery messageQuery) {
        // 查询留言数量
        Long count = messageMapper.selectCount(new LambdaQueryWrapper<Message>()
                .like(StringUtils.hasText(messageQuery.getKeyword()), Message::getNickname, messageQuery.getKeyword())
                .eq(Objects.nonNull(messageQuery.getIsCheck()), Message::getIsCheck, messageQuery.getIsCheck()));
        if (count == 0) {
            return new PageResult<>();
        }
        // 查询后台友链列表
        List<MessageBackResponse> messageBackRespList = messageMapper.selectBackMessageList(messageQuery);
        return new PageResult<>(messageBackRespList, count);
    }

    @Override
    public void addMessage(MessageRequest messageRequest) {
        // 对象转换, 将MessageRequest对象转换为Message对象
        Message newMessage = BeanCopyUtils.copyBean(messageRequest, Message.class);
        // 留言内容 需要过滤敏感词和防止xss攻击
        newMessage.setMessageContent(HTMLUtils.filter(messageRequest.getMessageContent()));
        String ipAddress = ServletUtil.getClientIP(httpServletRequest);
        newMessage.setIpAddress(ipAddress);
        newMessage.setIpSource(IpUtils.getIpSource(ipAddress));
        // 获取网站配置
        SiteConfig siteConfig = siteConfigService.getSiteConfig();
        // 获取网站配置中的留言审核状态 0 否 1 是
        // 因为添加留言时，默认留言审核状态为否，插入数据库需要将通过审核才能保存到数据库，前几步过滤的敏感词和防止xss攻击，审核状态应该为1。
        Integer messageCheck = siteConfig.getMessageCheck();
        newMessage.setIsCheck(messageCheck.equals(CommonConstant.FALSE) ? CommonConstant.TRUE : CommonConstant.FALSE);
        // 保存留言信息
        messageMapper.insert(newMessage);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public boolean removeByIds(List<Integer> messageIdList) {
        if (CollectionUtils.isEmpty(messageIdList)) {
            return false;
        } else {
            TableInfo tableInfo = TableInfoHelper.getTableInfo(this.getEntityClass());
            return tableInfo.isWithLogicDelete() && tableInfo.isWithUpdateFill() ? this.removeBatchByIds(messageIdList, true) : SqlHelper.retBool(this.getBaseMapper().deleteBatchIds(messageIdList));
        }
    }

    @Override
    public void updateMessageCheck(CheckRequest checkRequest) {
        // 修改留言审核状态
        List<Message> updateSuccessMessageList = checkRequest.getIdList().stream()
                .map(id -> {
                    Message updateSuccessMessage = Message.builder()
                            .id(id)
                            .isCheck(checkRequest.getIsCheck())
                            .build();
                    return updateSuccessMessage;
                })
                .collect(Collectors.toList());
        this.updateBatchById(updateSuccessMessageList);
    }


}
